package com.wh1200.mybatis.xmlless.resolver

import com.wh1200.kotlin.only
import com.wh1200.mybatis.xmlless.enums.MethodType
import java.util.*

/**
 *
 * @author 吴昊
 * @date 2024/1/15 10:58
 * @since v0.0.0
 * @version 1.0
 */
object MethodTypeResolver {

  fun resolveTypeFromName(words: Stack<String>): MethodType? {
    if (words.size == 1 && words.only() == "Clean") {
      words.clear()
      return MethodType.Clean
    }
    val typeWord = words.pop()
    val type = resolveTypeFromTypeWord(typeWord)
    if (words.lastOrNull() in listOf("All", "Batch", "One")) {
      words.pop()
      return type
    }
    if (words.isNotEmpty() && words.last() == "Or") {
      words.pop()
      val next = words.pop()
      if (next == "Update") {
        if (type != MethodType.Insert) {
          return null
        }
        return if (words.lastOrNull() in listOf("All", "Batch")) {
          words.pop()
          MethodType.InsertOrUpdate
        } else {
          MethodType.InsertOrUpdate
        }
      }
    }
    return type
  }

  private fun resolveTypeFromTypeWord(typeWord: String): MethodType? {
    return when (typeWord) {
      "List", "Find", "Select", "Query", "Search" -> MethodType.Select
      "Exists", "Count"                           -> MethodType.Count
      "Update"                                    -> MethodType.Update
      "Delete", "Remove"                          -> MethodType.Delete
      "Insert", "Save", "Add"                     -> MethodType.Insert
      else                                        -> null
    }
  }

}
